package com.yao.securitydemo.config;

import com.alibaba.fastjson.JSON;
import com.yao.securitydemo.filter.VerificationCodeFilter;
import com.yao.securitydemo.handler.MyAuthenticationFailureHandler;
import com.yao.securitydemo.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

/**
 * @author tututu
 * @description
 * @date 2022/4/22 23:05
 */
@Configuration
@EnableWebSecurity
public class SecurityConf extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.inMemoryAuthentication().withUser("lucy").password(passwordEncoder().encode("123456")).roles("");
        auth.userDetailsService(userDetailsService);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasRole("ADMIN")
                .antMatchers("/r/r2").hasRole("SALE")
                .antMatchers("/hello").permitAll()
                .antMatchers("/captcha.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/test/login")

                .successHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(Result.ok("欢迎登录")));
                })
                .failureHandler(new MyAuthenticationFailureHandler())
//                .failureHandler(((request, response, exception) -> {
//                    response.setContentType("application/json;charset=utf-8");
//                    PrintWriter writer = response.getWriter();
//                    writer.write(JSON.toJSONString(Result.error(200,exception.getMessage())));
//                }))
                .permitAll()
                .and()
                .csrf().disable();

        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }

//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("sale").password("123456").roles("SALE").build());
//        manager.createUser(User.withUsername("admin").password("123456").roles("ADMIN").build());
//        return manager;
//    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
